<?php
/**
 * Created by PhpStorm.
 * User: win7
 * Date: 2018/4/27
 * Time: 14:01
 */

namespace app\lib\exception;

use think\Config;
use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;
    // 需要返回客户端当前请求的URL路径
    private $url;
    // 框架会帮你传入Exception
    // 重写render，自定义异常处理
    public function render(\Exception $e) {
        if ($e instanceof BaseException) {
            // 判断是否自定义异常
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        } else {
//            Config::get('app_debug');
            if (config('app_debug')) {
                // 返回框架默认错误页面
                return parent::render($e);
            } else {
                // 这样对后端开发人员不友善，应该记录日志，不然生产环境下很难进行代码调试
                $this->msg = '服务器错误，不想告诉你';
                $this->errorCode = 999;
                $this->code = 500;
                $this->recordErrorLog($e);
            }
        }
        $request = Request::instance();
        $result = [
            'errorCode' => $this->errorCode,
            'msg' => $this->msg,
            'request_url' => $request->url()
        ];
        return json($result, $this->code);
    }
    private function recordErrorLog(\Exception $e) {
        // 日志初始化
        Log::init([
            'type'  =>  'File',
            'path'  =>  LOG_PATH,
            'level' =>  ['error']
        ]);
        // 错误级别低于error的日志不会记录
        Log::record($e->getMessage(), 'error');
    }
}